﻿using System;
using System.Web.UI.WebControls;
using eCommerce.core;
using eCommerce.core.Helpers;
using eCommerce.db.BORespository;

namespace eCommerce.web.Controls.Property
{
    public partial class PropertyByType : System.Web.UI.UserControl
    {        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var name = Utils.GetIdFromRequestString(Utils.Name, string.Empty);
                var parent_name = Utils.GetIdFromRequestString(Utils.Parent_Name, string.Empty);

                if (!string.IsNullOrEmpty(parent_name))
                    name = parent_name;

                if (Utils.GetSetting("SearchType", SettingType.String).ToString().IndexOf(name) != -1)
                {
                    GetByPropertyType(name);
                }
                else
                {
                    var child = CategoryBo.GetByUrl(name);
                    if (child != null)
                    {
                        var parent = CategoryBo.GetById(child.ParentId);
                        if (parent != null)
                            GetByPropertyType(parent.Url);                        
                    }    
                }
            }
        }

        private void GetByPropertyType(string typeName)
        {
            if (!string.IsNullOrEmpty(typeName))
            {
                var property = PropertyBo.GetByName(typeName);
                if (property != null)
                {
                    var lstProperty = PropertyBo.GetListByParentId(property.PropertyId);
                    if (lstProperty.Count > 0)
                    {
                        rptProperty.DataSource = lstProperty;
                        rptProperty.DataBind();
                    }
                }
            }
        }
        
        protected void rptProperty_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var propertyId          = Utils.ToInt32(((HiddenField)e.Item.FindControl("hfPropertyId")).Value);
                var rptPropertyValue    = (Repeater)e.Item.FindControl("rptPropertyValue");

                if (propertyId > 0)
                {
                    var lstPropertyValue = PropertyValueBo.GetListByPropertyId(propertyId);
                    if (lstPropertyValue.Count > 0)
                    {
                        rptPropertyValue.DataSource = lstPropertyValue;
                        rptPropertyValue.DataBind();
                    }
                }
            }
        }
    }
}